<template>
  <div class="notification-center">
    <!-- 通知图标 -->
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
      <el-popover
        placement="bottom-end"
        :width="400"
        trigger="click"
        popper-class="notification-popover"
      >
        <template #reference>
          <el-button :icon="Bell" circle class="notification-button" />
        </template>

        <!-- 通知列表 -->
        <div class="notification-list">
          <div class="notification-header">
            <h3>通知中心</h3>
            <el-button
              v-if="notifications.length > 0"
              @click="clearAll"
              type="text"
              size="small"
            >
              清空
            </el-button>
          </div>

          <div class="notification-content">
            <el-empty
              v-if="notifications.length === 0"
              description="暂无通知"
              :image-size="80"
            />

            <div
              v-for="notification in notifications"
              :key="notification.id"
              :class="['notification-item', { unread: !notification.read }]"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <el-icon v-if="notification.type === 'order'" color="#409eff" size="20">
                  <ShoppingCart />
                </el-icon>
                <el-icon v-else-if="notification.type === 'payment'" color="#67c23a" size="20">
                  <Money />
                </el-icon>
                <el-icon v-else-if="notification.type === 'favorite'" color="#e6a23c" size="20">
                  <Star />
                </el-icon>
                <el-icon v-else-if="notification.type === 'review'" color="#f56c6c" size="20">
                  <ChatDotRound />
                </el-icon>
                <el-icon v-else color="#909399" size="20">
                  <Bell />
                </el-icon>
              </div>
              <div class="notification-body">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.message }}</div>
                <div class="notification-time">{{ formatTime(notification.timestamp) }}</div>
              </div>
              <div class="notification-actions">
                <el-button
                  @click.stop="markAsRead(notification)"
                  type="text"
                  size="small"
                  v-if="!notification.read"
                >
                  标记已读
                </el-button>
                <el-button
                  @click.stop="removeNotification(notification)"
                  type="text"
                  size="small"
                  :icon="Delete"
                />
              </div>
            </div>
          </div>
        </div>
      </el-popover>
    </el-badge>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, ShoppingCart, Money, Star, ChatDotRound, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import wsClient from '../utils/websocket.js'

const router = useRouter()
const notifications = ref([])

// 计算未读数量
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

// 生成唯一ID
let notificationIdCounter = 1

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 添加通知
const addNotification = (notificationData) => {
  const notification = {
    id: notificationIdCounter++,
    ...notificationData,
    read: false,
    timestamp: notificationData.timestamp || new Date().toISOString()
  }
  
  notifications.value.unshift(notification)
  
  // 限制最多显示50条通知
  if (notifications.value.length > 50) {
    notifications.value = notifications.value.slice(0, 50)
  }

  // 显示浏览器通知（如果允许）
  if (Notification.permission === 'granted') {
    new Notification(notification.title, {
      body: notification.message,
      icon: '/favicon.ico'
    })
  }
}

// 标记为已读
const markAsRead = (notification) => {
  notification.read = true
}

// 移除通知
const removeNotification = (notification) => {
  const index = notifications.value.indexOf(notification)
  if (index > -1) {
    notifications.value.splice(index, 1)
  }
}

// 清空所有通知
const clearAll = () => {
  notifications.value = []
}

// 处理通知点击
const handleNotificationClick = (notification) => {
  markAsRead(notification)
  
  // 根据通知类型跳转到相应页面
  if (notification.type === 'order' && notification.data?.order_id) {
    router.push(`/orders/${notification.data.order_id}`)
  } else if (notification.type === 'favorite' && notification.data?.attraction_id) {
    // 可以跳转到景点详情页
    router.push(`/attraction/${notification.data.attraction_id}`)
  }
}

// WebSocket消息处理
const handleWebSocketMessage = (event) => {
  if (event.type === 'message' && event.data) {
    const notification = event.data
    addNotification(notification)
    
    // 显示消息提示
    ElMessage({
      message: notification.message || notification.title,
      type: notification.priority === 'urgent' ? 'error' : 
            notification.priority === 'high' ? 'success' : 'info',
      duration: 3000,
      showClose: true
    })
  }
}

// 请求浏览器通知权限
const requestNotificationPermission = () => {
  if ('Notification' in window && Notification.permission === 'default') {
    Notification.requestPermission()
  }
}

onMounted(() => {
  // 连接WebSocket
  const token = localStorage.getItem('token')
  if (token) {
    wsClient.connect(token)
    wsClient.onMessage(handleWebSocketMessage)
  }
  
  // 请求通知权限
  requestNotificationPermission()
})

onUnmounted(() => {
  wsClient.offMessage(handleWebSocketMessage)
})
</script>

<style scoped>
.notification-center {
  position: relative;
}

.notification-button {
  border: none;
  background: transparent;
}

.notification-list {
  max-height: 500px;
  overflow-y: auto;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.notification-content {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.3s;
}

.notification-item:hover {
  background: #f5f5f5;
}

.notification-item.unread {
  background: #f0f9ff;
}

.notification-item.unread:hover {
  background: #e0f2fe;
}

.notification-icon {
  margin-right: 12px;
  display: flex;
  align-items: flex-start;
  padding-top: 2px;
}

.notification-body {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-weight: 600;
  color: #333;
  font-size: 14px;
  margin-bottom: 4px;
}

.notification-message {
  color: #666;
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 4px;
  word-break: break-word;
}

.notification-time {
  color: #999;
  font-size: 12px;
}

.notification-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-left: 8px;
}

:deep(.notification-popover) {
  padding: 0 !important;
}
</style>

